import { link } from 'fs';
import { Component, Input, OnInit } from '@angular/core';
import { AlertController, ModalController } from '@ionic/angular';
import { AppGlobalService } from '../../shared/service/app-global.service';
import { HttpService } from '../../shared/service/http.service';
import { RecommendModalComponent } from '../recommend-modal/recommend-modal.component';
import { EventService } from 'src/app/shared/service/event.service';
import { NewInquiryPageModalComponent } from '../new-inquiry-page-modal/new-inquiry-page-modal.component';
import { ModalFromCenterLeave, ModalFromCenterEnter } from 'src/app/utils/transitions';
@Component({
  selector: 'app-two-link-style',
  templateUrl: './two-link-style.component.html',
  styleUrls: ['./two-link-style.component.scss'],
})
export class TwoLinkStyleComponent implements OnInit {

  @Input() tagData;
  constructor(
    private appGlobalService: AppGlobalService,
    private httpService: HttpService,
    private alertController: AlertController,
    public modalController: ModalController,
    private eventService: EventService,

  ) { }

  ngOnInit() { }


  buttonClick(button) {
    try {
      if (!button.phone) {
        if (button.link && button.link.type === 'model') {
          this.getVipData(button);
        } else if (button.link && button.link.type === 'page') {
          this.appGlobalService.openPage(button.link);
        } else {
          // 弹窗逻辑
          this.presentAlertSubmit(button);
        }

      } else {
        if (button.phone !== '') {
          this.call(button.phone, button.label);
        }
      }
    } catch (error) {
      console.log('error----->' + JSON.stringify(error));
    }
  }
  async call(mobile, name) {
    const alert = await this.alertController.create({
      header: name,
      message: mobile,
      buttons: [
        {
          text: '取消',
          role: 'cancel',
          cssClass: 'secondary'
        }, {
          text: '拨打',
          handler: () => {
            this.httpService.changeCallNumber(mobile);
          }
        }
      ]
    });
    await alert.present();
  }
  getVipData(item) {
    const params = {
      sessionId: localStorage.getItem("sessionId"),
      pageId: item.link.target,
      params: item.link.params
    };
    this.httpService.post('application/page', params, res => {
      // console.log(JSON.parse(res.script));
      // const tmpData = JSON.parse(res.script).views[0].tags[0].data;
      const tags = JSON.parse(res.script).views[0].tags;
      const len = tags.length;
      for (let i = 0; i < len; i++) {
        const tmpTag = tags[i];
        const tmpStyle = tags[i].style;
        if (tmpStyle === 'appVipPopupTag') {
          this.showRecommenMessageVip(tmpTag.data);
          break;
        } else if (tmpStyle === 'tipsDivTag') {
          if (tmpTag.data && tmpTag.data.tipsDiv) {
            tmpTag.data.tipsDiv.styleName = tmpTag.name;
            this.showRecommenTip(tmpTag.data.tipsDiv);
          } else {
            this.showRecommenTip(tmpTag);
          }
          break;
        } else if (tmpStyle === 'inquiry-page-style') {
          if (tmpTag.data.cssType && tmpTag.data.cssType === '1') {
            this.presentAlertDialogConfirmCssType1(tmpTag);
          } else {
            this.presentAlertDialogConfirm(tmpTag);
          }
          break;
        }
      }
    });
  }

  // 购买信息 开通会员
  async showRecommenMessageVip(vipData) {
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: 'recommend-modal-auto-heigth',
      component: RecommendModalComponent,
      componentProps: { vipData },
      leaveAnimation: ModalFromCenterLeave,
      enterAnimation: ModalFromCenterEnter
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
  }

  async showRecommenTip(tmpTagData) {
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: 'recommend-modal',
      component: RecommendModalComponent,
      componentProps: { tipData: tmpTagData },
      leaveAnimation: ModalFromCenterLeave,
      enterAnimation: ModalFromCenterEnter
    });
    await modal.present();
    // 监听销毁的事件
    await modal.onDidDismiss().then((res) => {
      // this.appGlobalService.popTarget();
      // this.appGlobalService.goBack();
    }); // 获取关闭传回的值
  }

  async presentAlertSubmit(data) {
    let msg = data.label;
    if (data.text1 && data.text2 && data.text3) {
      msg = data.text1 + data.text2 + data.text3;
    }
    const alert = await this.alertController.create({
      header: msg,
      // message: msg,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: "确定",
          handler: () => {
            const params = {
              content: data.submit.content,
              id: data.submit.id,
              sessionId: localStorage.getItem("sessionId")
            };
            this.submit(params);
          }
        }
      ]
    });

    await alert.present();
  }

  submit(params) {
    this.httpService.post("application/submit", params, res => {
      if (res.message) {
        this.appGlobalService.showToast(res.message, 1500, "middle");
      }
      // 邀约
      if (params.content && params.content.way === "4") {
        if (res.data && res.data.eventResult && res.data.eventResult.indexOf("#") > -1) {
          const msg = res.data.eventResult.split("#")[0];
          this.appGlobalService.showToast(msg, 1500, "middle");

          const paramsString = res.data.eventResult.split("#")[1];
          // tslint:disable-next-line:no-shadowed-variable
          const params: any = {};
          const paramArray = paramsString.split(",");
          // tslint:disable-next-line:prefer-for-of
          for (let i = 0; i < paramArray.length; i++) {
            const p = paramArray[i].split(":");
            params[p[0]] = p[1];
          }
          this.sendInvitationMsg(params);
        }
      }
    });
  }
  sendInvitationMsg(params) {
    if (localStorage.getItem('userId') !== 'null') {
      if (params.opportunity_id) {
        const tmpMsgBody = {
          auth: true,
          opportunity_id: params.opportunity_id,
          imags: params.imags,
          pluginId: params.pluginId,
          title: params.title,
          big_district: params.big_district ? params.big_district : '',
          district: params.district ? params.district : '',
          area: params.area ? params.area : '',
          industry: params.industry ? params.industry : '',
          rentunit: params.rentunit ? params.rentunit : '元/月',
          rent: params.rent ? params.rent : '',
          transfer_fee: params.transfer_fee ? params.transfer_fee : '',
          from: localStorage.getItem("connUserId"),
          type: "opp"
        };
        // params.opportunity_id  params.current_opportunity_id
        // tslint:disable-next-line:max-line-length
        this.httpService.getImIdForInviteMsg(JSON.stringify(tmpMsgBody), params.opportunity_id, params.current_opportunity_id, (resItem) => {
          localStorage.removeItem('needRefresh');
          localStorage.setItem('onSendWebSocketMessageTag', 'true');
          const nowDate = Date.now();
          const message = {
            text: params.title,
            toId: resItem.toId,
            fromId: localStorage.getItem("connUserId"),
            key: resItem.id,
            type: 'opp',
            rentunit: params.rentunit ? params.rentunit : '元/月',
            opportunity_id: params.opportunity_id,
            // tslint:disable-next-line:max-line-length
            title: params.title,
            imags: params.imags,
            pluginId: params.pluginId,
            big_district: params.big_district ? params.big_district : '',
            district: params.district ? params.district : '',
            area: params.area ? params.area : '',
            industry: params.industry ? params.industry : '',
            rent: params.rent ? params.rent : '',
            transfer_fee: params.transfer_fee ? params.transfer_fee : '',
            nowDate
          };
          this.eventService.eventEmit.emit("onSendWebSocketMessage", message);
        });

      }
    }
  }

  async presentAlertDialogConfirm(thisTagData) {
    try {
      const alert = await this.alertController.create({
        cssClass: 'my-custom-class',
        header: '',
        // tslint:disable-next-line:max-line-length
        message: '<span "height:2.75rem;font-size:1rem;font-weight:bold;color:rgba(39,40,46,1);">' + thisTagData.data.title + '</span>',
        buttons: [
          {
            text: thisTagData.data.cancel,
            role: 'cancel',
            handler: (blah) => {
              // // this.appGlobalService.isShowInquiryPageModal = true;\
              // this.appGlobalService.popTarget();
              // this.appGlobalService.goBack();
            }
          }, {
            text: thisTagData.data.button ?
              thisTagData.data.button.label :
              thisTagData.data.buttonLink[0].label,
            cssClass: 'custom-ok-btn',
            handler: () => {
              this.appGlobalService.isShowInquiryPageModal = true;

              if (thisTagData.data.button) {
                if (thisTagData.data.button.submit !== undefined) {
                  const params = {
                    content: thisTagData.data.button.submit.content,
                    id: thisTagData.data.button.submit.id,
                    sessionId: localStorage.getItem('sessionId')
                  };

                  this.httpService.post('application/submit', params, res => {
                    // 请求数据成功
                    if (res.success === true) {
                      this.appGlobalService.showToast(res.message, 2000, 'middle');
                      setTimeout(() => {
                        localStorage.setItem('needRefresh', 'true');
                      }, 2000);
                    } else {
                      // 请求数据失败
                      this.appGlobalService.showToast(res.message, 2000, 'middle');
                    }
                  });

                }

                if (!localStorage.getItem('userInfo') && thisTagData.data.button.link) {
                  const pageParams = {
                    pageId: thisTagData.data.button.link.target,
                    params: thisTagData.data.button.link.params,
                    sessionId: localStorage.getItem('sessionId')
                  };
                  this.appGlobalService.goToForward(pageParams);
                }
              } else if (thisTagData.data.buttonLink) {
                if (!localStorage.getItem('userInfo') && thisTagData.data.buttonLink[0].link) {
                  const pageParams = {
                    pageId: thisTagData.data.buttonLink[0].link.target,
                    params: thisTagData.data.buttonLink[0].link.params,
                    sessionId: localStorage.getItem('sessionId')
                  };
                  this.appGlobalService.goToForward(pageParams);
                }
              }
            }
          }
        ]
      });
      await alert.present();
    } catch (error) {
      console.log('error------>' + JSON.stringify(error));
    }
  }


  async presentAlertDialogConfirmCssType1(thisTagData) {
    try {
      const modal = await this.modalController.create({
        showBackdrop: true,
        cssClass: 'recommend-modal',
        animated: false,
        component: NewInquiryPageModalComponent,
        componentProps: { tagData: thisTagData.data }
      });
      await modal.present();
      await modal.onDidDismiss().then((res) => {

      });
    } catch (error) {
    }
  }

}
